<template>
  <div>
    <Steps v-if="step>1" :step="step" />
    <Step1 v-if="step === 1" ref="step1" @click="selectIndustryHandle" />
    <Step2 v-if="step === 2" :id="id" ref="step2" :form-detail="form2" />
    <Step3 v-if="step === 3" :id="id" ref="step3" :form-detail="form3" />
    <Step4 v-if="step === 4" :id="id" ref="step4" :industry-code="industryCode" :form-detail="form4" />
    <Step5 v-if="step >=5" ref="step5" :type="'enter'" :status="approveStatus" @reason="showReason" @sign="gotoSign" @resubmit="reSubmit" />

    <div v-if="step>1 && step<5" class="handle-bottom-box">
      <el-button @click="goBack">返回</el-button>
      <el-button v-if="step>2 && approveType === 0" type="primary" @click="beforeStep">上一步</el-button>
      <el-button type="primary" @click="saveHandle(true)">保存草稿</el-button>
      <el-button v-if="step===4" type="primary" @click="saveHandle(false)">提交</el-button>
      <el-button v-if="step<4" type="primary" @click="nextHandle(false)">下一步</el-button>
    </div>

    <Reject
      v-if="showReject"
      :reject-form="rejectForm"
      @close="closeHandle"
    />

  </div>
</template>

<script>
import Steps from './Steps.vue'
import Step1 from './Step1.vue'
import Step2 from './Step2.vue'
import Step3 from './Step3.vue'
import Step4 from './Step4.vue'
import Step5 from '@/components/Approve/Result.vue'
import Reject from '@/components/Approve/Reject.vue'
import {
  createAptitude,
  createPayment,
  createSite,
  getLatestUnFinishedEnterprise
} from '@/api/enter'
import { getLatestApprove } from '@/api/common'
import { getCurrentEnterprise } from '@/utils/auth'
export default {
  name: 'Enter',
  components: {
    Steps,
    Step1,
    Step2,
    Step3,
    Step4,
    Step5,
    Reject

  },
  data() {
    return {
      step: 0,
      id: '',
      approveType: 0, // 0 企业入驻  1 站点入驻
      approveDetail: {},
      enterpriseDetail: {},
      approveStatus: null,
      industryCode: '',
      form2: {},
      form3: {},
      form4: [],
      showReject: false,
      rejectForm: {},
      currentEnterprise: {}
    }
  },

  watch: {
    enterpriseDetail(value) {
      const {
        id = '',
        mainBodyType = 0,
        aptitudeImage = '',
        socialCreditCode = '',
        infoName = '',
        belongingPlace = 0,
        idPhoto = '',
        idCardNumber = '',
        aptitudeName = '',
        phone = '',
        accountType = 1,
        bankNo = '',
        bankAddress = [],
        bankName = '',
        subBankName = '',
        userCardImg = '',
        bankReservePhone = '',
        openType = '',
        userName = '',
        siteResps = []
      } = value
      if (id) {
        this.form2 = {
          mainBodyType,
          aptitudeImage,
          socialCreditCode,
          infoName,
          belongingPlace,
          idPhoto,
          idCardNumber,
          aptitudeName,
          phone
        }
        this.form3 = {
          accountType,
          bankNo,
          bankAddress: bankAddress ? bankAddress.split(',') : [],
          bankName,
          subBankName,
          userCardImg,
          bankReservePhone,
          openType,
          userName
        }
        this.form4 = siteResps.map(item => {
          const phones = item.phoneNumbers ? item.phoneNumbers.split(',') : []
          const phoneNumbers = phones.map((item) => ({ phone: item }))
          const businessType = item.businessType ? item.businessType.split(',') : []
          const scenicAddress = item.scenicAddress ? item.scenicAddress.split(',') : []
          const coordinate = `${item.lon},${item.lat}`
          return {
            ...item,
            phoneNumbers,
            businessType,
            scenicAddress,
            coordinate
          }
        })
      }
    }
  },

  created() {
    this.approveType = Number(this.$route.query.approveType) || 0
    this.getLatestApprove()
    this.currentEnterprise = getCurrentEnterprise()
  },

  methods: {

    getLatestApprove() {
      const data = {
        approveType: this.approveType
      }
      getLatestApprove(data).then(res => {
        const signFlag = res?.enterpriseResp?.siteResps[0]?.agreementId
        if (signFlag) {
          // 签约完成，直接进入第一步初始状态
          this.step = 1
        } else {
          this.approveDetail = res || {}
          this.industryCode = res.industryCode
          this.approveStatus = this.approveDetail.approveStatus
          this.enterpriseDetail = this.approveDetail.enterpriseResp || {}
          this.id = this.enterpriseDetail.id
          if (this.approveStatus === -1) {
            // 待审核  进入第五步
            this.step = 5
          } else if (this.approveStatus === 0) {
            // 审核拒绝 进入第六步
            this.step = 6
          } else if (this.approveStatus === 1) {
            // 审核完成 进入第6步
            this.step = 6
          } else {
            // 其他情况进入第一步
            this.step = 1
          }
        }
      }).catch(() => {})
    },

    // 获取草稿
    getLatestUnFinishedEnterprise() {
      const data = {
        industryCode: this.industryCode
      }
      return getLatestUnFinishedEnterprise(data).then(res => {
        this.id = res?.id
        this.enterpriseDetail = res || {}
      }).catch(() => {})
    },

    // 重新提交
    reSubmit() {
      if (this.approveType === 0) {
        this.step = 2
      } else {
        this.step = 4
      }
    },

    // 返回
    goBack() {
      this.$router.back()
    },

    // 上一步
    async beforeStep() {
      await this.getLatestUnFinishedEnterprise()
      this.step = this.step - 1
    },

    // 下一步
    nextHandle(flag) {
      if (this.step === 2) {
        this.createAptitude(flag)
      } else if (this.step === 3) {
        this.createPayment(flag)
      }
    },

    // 保存
    saveHandle(flag) {
      if (this.step === 2) {
        this.createAptitude(flag)
      } else if (this.step === 3) {
        this.createPayment(flag)
      } else if (this.step === 4) {
        this.createSite(flag)
      }
    },

    // 第一步 选择行业，查询未完成企业信息
    async selectIndustryHandle(industryCode) {
      this.industryCode = industryCode
      await this.getLatestUnFinishedEnterprise()
      if (this.approveType === 0) {
        this.step = 2
      } else {
        this.step = 4
      }
    },

    // 第二步 保存资质信息
    async createAptitude(draft) {
      if (!draft) {
        await this.$refs.step2.$refs.form.validate()
      }
      const data = {
        industryCode: this.industryCode,
        draft,
        ...this.$refs.step2.form
      }
      createAptitude(data).then((res) => {
        this.enterpriseDetail = res
        if (draft) {
          this.$message.success('保存草稿成功')
        } else {
          this.step = 3
        }
      }).catch(() => {})
    },

    // 第三部 保存收款信息
    async createPayment(draft) {
      if (!draft) {
        await this.$refs.step3.$refs.form.validate()
      }
      const bankAddress = this.$refs.step3.form.bankAddress.join(',')
      const data = {
        industryCode: this.industryCode,
        draft,
        ...this.$refs.step3.form,
        bankAddress
      }
      console.log(data)
      createPayment(data).then((res) => {
        this.enterpriseDetail = res
        if (draft) {
          this.$message.success('保存草稿成功')
        } else {
          this.step = 4
        }
      }).catch(() => {})
    },

    // 第四步 保存门店信息
    async createSite(draft) {
      if (!draft) {
        await this.$refs.step4.$refs.form.validate()
      }
      const reqList = this.$refs.step4.shopList.map(item => {
        const lnglat = item.coordinate?.split(',') || []
        const phoneNumbers = []
        item.phoneNumbers?.map(phoneItem => {
          if (phoneItem.phone) {
            phoneNumbers.push(phoneItem.phone)
          }
        })
        return {
          ...item,
          lon: lnglat[0] ? lnglat[0] : '',
          lat: lnglat[1] ? lnglat[1] : '',
          phoneNumbers: phoneNumbers.length ? phoneNumbers.join(',') : '',
          businessType: item.businessType ? item.businessType?.join(',') : '',
          scenicAddress: item.scenicAddress ? item.scenicAddress?.join(',') : '',
          industryCode: this.industryCode,
          draft,
          enterpriseId: this.approveType === 0 ? undefined : this.currentEnterprise?.id
        }
      })
      const data = {
        approveType: this.approveType,
        reqList
      }
      console.log(data)
      createSite(data).then((res) => {
        this.enterpriseDetail = res
        this.approveStatus = res?.approveStatus
        if (draft) {
          this.$message.success('保存草稿成功')
        } else {
          this.step = 5
        }
      }).catch(() => {})
    },

    // 展示拒绝原因
    showReason() {
      const { rejectReason = '', rejectFileUrl = '' } = this.approveDetail
      this.rejectForm = {
        rejectReason,
        rejectFileUrl
      }
      this.showReject = true
    },

    // 关闭
    closeHandle() {
      this.showReject = false
    },

    // 去签署协议
    gotoSign() {
      const { id, siteResps } = this.enterpriseDetail
      const siteList = []
      siteResps.map(item => {
        siteList.push(item.id)
      })
      this.$router.push({
        path: '/enterProcess/enter/sign',
        query: {
          id,
          industryCode: this.industryCode,
          siteIds: siteList.join(',')
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.handle-bottom-box{
  position: fixed;
  z-index: 10;
  right: 0;
  bottom: 0;
  height: 60px;
  width: 100%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
}
</style>
